import { createStore } from "vuex";
import axios from "axios";

export default createStore({
  state: {
    user: null,
  },
  getters: {
    user: (state) => {
      return state.user || JSON.parse(sessionStorage.getItem("UserInfo"));
    },
  },
  mutations: {
    setLogin(state, data) {
      sessionStorage.setItem("Authorization", data.token);
      sessionStorage.setItem("UserInfo", JSON.stringify(data.user));
      state.user = data.user;
    },
    setLoginOut(state) {
      sessionStorage.removeItem("UserInfo");
      sessionStorage.removeItem("Authorization");
      state.user = null;
    },
  },
  actions: {
    login({ commit }, obj) {
      return new Promise((resolve, reject) => {
        axios
          .post("/account/login", obj)
          .then((res) => {
            const { success, data, msg } = res;
            if (success) {
              commit("setLogin", data);
              resolve();
            } else {
              reject(msg);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});
